'use strict';

const BaseController = require('./base');

class DeviceController extends BaseController {
  get _service() {
    return 'device';
  }

  async create() {
    const { ctx } = this;
    const { name, parentId } = ctx.params();
    const result = await this._getService().create({ name, parentId });
    if (result) {
      this.success();
    } else {
      this.error('创建设备失败');
    }
  }

  async update() {
    const { ctx } = this;
    const { name } = ctx.params();
    const { id } = ctx.params;
    const result = await this._getService().update({ name, id });
    if (result) {
      this.success();
    } else {
      this.error('更新设备失败');
    }
  }

  async destroy() {
    await this._destory('删除设备失败');
  }

  async show() {
    await this._show('获取设备失败');
  }

  async index() {
    const { ctx } = this;
    const { name, prop, sort, pageIndex, pageSize } = ctx.params();
    const { createdAt } = ctx.queries;
    const tempResult = await this._getService().findList({ name, prop, sort, pageIndex, pageSize, createdAt });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取设备失败');
    }
  }

  // 获取顶级设备
  async top() {
    const result = await this._getService().findAll({ parentId: 1 });
    if (result) {
      this.success(result);
    } else {
      this.error('获取设备失败');
    }
  }

  async all() {
    const { ctx } = this;
    const tempResult = await this._getService().findAll();
    const result = ctx.helper.convert(tempResult);
    if (result) {
      this.success(result);
    } else {
      this.error('获取设备失败');
    }
  }
}

module.exports = DeviceController;
